const DataSchema = require('./DataSchema');

/**
 * DataQuery - Handles data retrieval operations
 */
class DataQuery {
    /**
     * Query data with pagination and filtering
     */
    static async queryData(caseKnex, options) {
        const { dataType, page = 1, pageSize = 100, filters = {} } = options;
        const tableName = DataSchema.getTableName(dataType);

        // Ensure table exists to prevent SQLITE_ERROR
        await DataSchema.ensureTableExists(caseKnex, tableName, dataType);

        let query = caseKnex(tableName);

        // Apply filters
        Object.entries(filters).forEach(([key, value]) => {
            if (value) {
                query = query.where(key, 'like', `%${value}%`);
            }
        });

        // Get total count
        const [{ count }] = await query.clone().count('* as count');

        // Get paginated results
        const data = await query
            .orderBy('id', 'desc')
            .limit(pageSize)
            .offset((page - 1) * pageSize);

        return {
            data,
            total: count,
            page,
            pageSize,
            totalPages: Math.ceil(count / pageSize)
        };
    }
}

module.exports = DataQuery;
